package com.snsoft.kidstube;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import net.htmlparser.jericho.*;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.Browser;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.content.Context;
import android.content.res.Configuration;
import android.database.Cursor;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebStorage;
import android.webkit.WebChromeClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.OnTabChangeListener;
import android.graphics.Bitmap;

import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.*;

import net.daum.adam.publisher.AdView;
import net.daum.adam.publisher.AdView.OnAdClickedListener;
import net.daum.adam.publisher.AdView.OnAdClosedListener;
import net.daum.adam.publisher.AdView.OnAdFailedListener;
import net.daum.adam.publisher.AdView.OnAdLoadedListener;
import net.daum.adam.publisher.AdView.OnAdWillLoadListener;
import net.daum.adam.publisher.impl.AdError;
import net.daum.adam.publisher.AdView.AnimationType;


public class KidsTubeActivity extends TabActivity implements OnTabChangeListener
{
	public WebView wv;
	public Dialog dialog;
	public TabHost th;
	public FrameLayout fl;
	private String wvurl = "";
	private String param = "";

	File f; 
	
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	public static final int DIALOG_QUIT_ALERT = 1;
	public static final int DIALOG_DOWNLOAD_MGT = 2;
	public static final int DIALOG_LIMIT_ALERT = 3;
	public static final int DIALOG_DOWNLOAD_CHECK = 4;

	
    private ProgressDialog mProgressDialog;
    
    private CharSequence[] dn_items;
    private String[] dn_url;
    private String video_id;
    private String title;
    
    SharedPreferences preferenceManager;
    DownloadManager downloadManager;
    final String strPref_Download_ID = "PREF_DOWNLOAD_ID";

    
    private com.google.ads.AdView admobView = null;
	private net.daum.adam.publisher.AdView adamView = null;
	private static final String LOGTAG = "Adam";
	
	private ImageView imgAd;
	private AdRequest adRequest;
	
    public static Activity activity;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        activity = KidsTubeActivity.this; 

        setContentView(R.layout.main);

        wv = (WebView)findViewById(R.id.webview);
        
        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setLoadsImagesAutomatically(true);
        wv.getSettings().setLightTouchEnabled(true);
        wv.getSettings().setPluginsEnabled(true);
        wv.setVerticalScrollbarOverlay(true);
        wv.setHorizontalScrollBarEnabled(false);
        wv.setBackgroundColor(0xFFF0F0F0);

        // Loading dialog set
        dialog = new Dialog(activity, R.style.SNDialog);
        dialog.addContentView(new ProgressBar(this), new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        
        // Download set
        preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);
        
        if(android.os.Build.VERSION.SDK_INT > 8)
        	downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        
        wv.setWebViewClient(new WebViewClient()
        {
        	@Override
        	public boolean shouldOverrideUrlLoading(WebView view, String url)
        	{
        		// Allow new window(youtube)
        		if(url.startsWith("http://www.youtube.com"))
        		{	
        			playYouTube(url);

        		}
        		else if(url.startsWith("http://kidstube.kr/all"))
        		{
        			String pl_id = url.substring(url.indexOf("=") + 1);
                    
        			if(android.os.Build.VERSION.SDK_INT >= 15)
        			{
        				playYouTube("http://www.youtube.com/playlist?list=" + pl_id);
        			}
        			else
        			{
	        			Intent videoClient = new Intent(getApplication(), YoutubePlayerActivity.class);
	                	videoClient.putExtra("PL_ID", pl_id);
	                	
	                	startActivity(videoClient);
        			}
        		}
        		else if(url.startsWith("http://kidstube.kr/download"))
        		{
        			showDialog(DIALOG_LIMIT_ALERT);
        			//startDownload(url);        				
        		}
        		else if(url.startsWith("http://kidstube.kr/play"))
        		{
        			startPlay(url);
        		}
        		else if(url.startsWith("http://kidstube.kr/delete"))
        		{
        			startDelete(url);
        		}
        		else if(url.indexOf("#") > 0)
        		{
        			param = url.substring(url.indexOf("#") + 1);
        			view.loadUrl(url.substring(0, url.indexOf("#")));
        		}
        		else
        			view.loadUrl(url);
        		
        		return true;
        	}
        	
        	
        	@Override     
        	public void onPageStarted(WebView view, String url, Bitmap favicon) 
        	{
        		if(dialog != null)
        			dialog.show();
        	} 
        	
        	@Override     
        	public void onPageFinished(WebView view, String url) 
        	{
        		wvurl = wv.getUrl();
        		
        		if(dialog != null && dialog.isShowing())
        		{
        			dialog.dismiss();
        		}
        		
        		if(!param.equals("") && (url.matches(".*cate_list.*") || url.matches(".*featured_list.*")))
        		{
        			view.loadUrl("javascript:Load('" + param + "')");
        		}
        	}      
        	
        	@Override
        	public void onReceivedError(WebView view, int errorCode,String description, String failingUrl)
        	{
        		wv.loadData("<html><body align='center' valign='center'></body></html>", "text/html", "UTF-8");
        		Toast.makeText(activity, "Network unavailable. Please try again later.", Toast.LENGTH_LONG).show();
        	}
        });
		
        // HTML5 Setting
        String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        String cachePath = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
                
        wv.getSettings().setDatabasePath(databasePath);
        wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        wv.getSettings().setDomStorageEnabled(true);
        wv.getSettings().setDatabaseEnabled(true);
        
        // Set cache size to 8 mb by default. should be more than enough
        wv.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        wv.getSettings().setAppCachePath(cachePath);
        wv.getSettings().setAppCacheEnabled(true);
        wv.getSettings().setAllowFileAccess(true);
        wv.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
		
        wv.setWebChromeClient(new WebChromeClient()
        {
        	@Override
        	public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) 
        	{              
        		quotaUpdater.updateQuota(estimatedSize * 2);
        	}
        	
        	@Override
            public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) 
        	{
                quotaUpdater.updateQuota(spaceNeeded * 2);
            }
        });
        
        wv.loadUrl("file:///android_asset/index.html");
        
        // Tab Setting
        th = getTabHost();
        
        th.addTab(th.newTabSpec("tab1").setIndicator("home", getResources().getDrawable(R.drawable.tab1)).setContent(R.id.webview));
        th.addTab(th.newTabSpec("tab2").setIndicator("category", getResources().getDrawable(R.drawable.tab2)).setContent(R.id.webview));
        th.addTab(th.newTabSpec("tab3").setIndicator("download", getResources().getDrawable(R.drawable.tab3)).setContent(R.id.webview));
        th.addTab(th.newTabSpec("tab4").setIndicator("search", getResources().getDrawable(R.drawable.tab4)).setContent(R.id.webview));
        
        th.getCurrentView().setVisibility(View.VISIBLE);
        th.setCurrentTab(0);
        
        th.setOnTabChangedListener(this);       
        
        for(int tab = 0; tab < th.getTabWidget().getChildCount(); tab++)
        {
        	th.getTabWidget().getChildAt(tab).setBackgroundResource(R.drawable.tab_bg);
        }
        
        /*
        // S&SOFT AD
        imgAd = (ImageView) findViewById(R.id.adimgView);
        
        imgAd.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	String emailAddressList[] = {"almostsales@naver.com", "snsoftkr@gmail.com"};
            	  
        	   Intent intent = new Intent(Intent.ACTION_SEND); 
        	   intent.setType("plain/text");
        	   intent.putExtra(Intent.EXTRA_EMAIL, emailAddressList);  
        	   intent.putExtra(Intent.EXTRA_SUBJECT, "[S&TV-KIDS AD]"); 
        	   intent.putExtra(Intent.EXTRA_TEXT, ""); 
        	   startActivity(Intent.createChooser(intent, "Choose your email app."));
            }
        });
        
        */
        
        // Admob Setting
        admobView = (com.google.ads.AdView)this.findViewById(R.id.admobView);
        adRequest = new AdRequest();
        //adRequest.addTestDevice(AdRequest.TEST_EMULATOR);					// Emulator
        //adRequest.addTestDevice("444673C1328A36BB3EB297C2A231C68B");		// Test Android Device
        admobView.loadAd(adRequest);
        admobView.setAdListener(new AdListener() 
        {
        	public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) 
        	{
			}

			public void onDismissScreen(Ad arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onLeaveApplication(Ad arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onPresentScreen(Ad arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onReceiveAd(Ad arg0) {
				// TODO Auto-generated method stub
				
				//imgAd.setVisibility(View.GONE);			// 이미지 숨김
			}

        });
        
        
        // adam 실행
        //initAdam();
        
            
        //admobView.setVisibility(View.GONE);		// 애드몹 숨김
        
        /*
        // 10초 후 광고 실행
        Handler handler = new Handler(); 
        handler.postDelayed(new Runnable() { 
             public void run() {
            	admobView.loadAd(adRequest);
            	admobView.setVisibility(View.VISIBLE);			// 애드몹 표시
 				admobView.bringToFront();						// 애드몹 상위
             } 
        }, 10000);
        
        */
    }

    public void initAdam() {
		// Ad@m sdk 초기화 시작
    	adamView = (AdView) findViewById(R.id.adamView);

		// 광고 클릭시 실행할 리스너
    	adamView.setOnAdClickedListener(new OnAdClickedListener() {
			public void OnAdClicked() {
				Log.i(LOGTAG, "광고를 클릭했습니다.");
			}
		});

		// 광고 내려받기 실패했을 경우에 실행할 리스너
    	adamView.setOnAdFailedListener(new OnAdFailedListener() {
			public void OnAdFailed(AdError arg0, String arg1) {
				//Log.w(LOGTAG, arg1);
				
				//adamView.setVisibility(View.INVISIBLE);		// 아담 숨김
				
				admobView.setVisibility(View.VISIBLE);			// 애드몹 표시
				admobView.bringToFront();						// 애드몹 상위
			}
		});

		// 광고를 정상적으로 내려받았을 경우에 실행할 리스너
    	adamView.setOnAdLoadedListener(new OnAdLoadedListener() {
			public void OnAdLoaded() {
				Log.i(LOGTAG, "광고가 정상적으로 로딩되었습니다.");
				
				//imgAd.setVisibility(View.GONE);			// 이미지 숨김
				
				admobView.setVisibility(View.GONE);		// 애드몹 숨김
				
				adamView.setVisibility(View.VISIBLE);		// 아담 표시
				adamView.bringToFront();					// 아담 상위
			}
		});

		// 광고를 불러올때 실행할 리스너
    	adamView.setOnAdWillLoadListener(new OnAdWillLoadListener() {
			public void OnAdWillLoad(String arg1) {
				Log.i(LOGTAG, "광고를 불러옵니다. : " + arg1);
			}
		});

		// 광고를 닫았을때 실행할 리스너
    	adamView.setOnAdClosedListener(new OnAdClosedListener() {
			public void OnAdClosed() {
				Log.i(LOGTAG, "광고를 닫았습니다.");
			}
		});

		// 할당 받은 clientId 설정
    	//adamView.setClientId("2c54Z3JT137787f907c");			// Play
    	adamView.setClientId("2c53Z3IT137787ba9c2");			// Tstore
  		
    	adamView.setRequestInterval(12);

		// Animation 효과 : 기본 값은 AnimationType.NONE
    	adamView.setAnimationType(AnimationType.FLIP_HORIZONTAL);

    	adamView.setVisibility(View.VISIBLE);
	}
   
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
    	if(keyCode == KeyEvent.KEYCODE_BACK)
    	{
    		if(wvurl.matches(".*cate_list.*") && wv.canGoBack())
        	{
    			wv.loadUrl("file:///android_asset/category.html");
        		return true;
        	}
    		else if(wvurl.matches(".*featured_list.*") && wv.canGoBack())
        	{
    			wv.loadUrl("file:///android_asset/index.html");
        		return true;
        	}
    		else
    		{
    			showDialog(DIALOG_QUIT_ALERT);
	    		return true;
    		}
    	}
    	return super.onKeyDown(keyCode, event);
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
    	super.onConfigurationChanged(newConfig);
    }

    public void onTabChanged(String tabId) 
	{
    	if(tabId.equals("tab1"))
    	{
    		wv.loadUrl("file:///android_asset/index.html");
    	}
    	else if(tabId.equals("tab2"))
    	{
    		wv.loadUrl("file:///android_asset/category.html");
    	}
    	else if(tabId.equals("tab3"))
    	{
    		//wv.loadUrl("file:///android_asset/downloads.html");
    		showDialog(DIALOG_LIMIT_ALERT);
    	}
    	else if(tabId.equals("tab4"))
    	{
    		wv.loadUrl("file:///android_asset/search.html");
    	}
    	
	}

    @Override
    public void onDestroy() 
    {
      super.onDestroy();
    }
    
    // youtube play
    private void playYouTube(String url)
    {
		Intent videoClient = new Intent(Intent.ACTION_VIEW);
        videoClient.setData(Uri.parse(url));					//you can try here your own video url
        videoClient.setPackage("com.google.android.youtube");
        
        try
        {
            startActivity(videoClient);
        }
        catch(ActivityNotFoundException excp)
        {	
        	videoClient = null;
        	videoClient = new Intent(Intent.ACTION_VIEW);
        	videoClient.setData(Uri.parse(url));
        	videoClient.addCategory(Intent.CATEGORY_BROWSABLE);
        	videoClient.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
			startActivity(videoClient);
			
        }
    }
    
    private void startDownload(String url) 
    {
		video_id = url.substring(url.lastIndexOf("v=") + 2);
		
		new DownloadUrlAsync().execute(video_id);
    }
    
    private void startPlay(String url) 
    {
    	String mp4id = url.substring(url.lastIndexOf("v=") + 2);
    	String sd = Environment.getExternalStorageDirectory().toString();
		File path = new File(sd + "/KidsTube", mp4id + ".mp4");
		
		if(path.isFile())
		{
			Intent intent = new Intent();  
            intent.setAction(android.content.Intent.ACTION_VIEW);  
            intent.setDataAndType(Uri.fromFile(path), "video/*");  
            startActivity(intent);
		}
		else
		{
			startDownload("http://kidstube.kr/download.php?v=" + mp4id);
		}
    }
    
    private void startDelete(String url) 
    {
    	String mp4id = url.substring(url.lastIndexOf("v=") + 2);
    	String sd = Environment.getExternalStorageDirectory().toString();
		File path = new File(sd + "/KidsTube", mp4id + ".mp4");
		
		if(path.isFile())
		{
			path.delete();
		}
    }
 
    @Override
    protected Dialog onCreateDialog(int id) 
    {
    	super.onCreateDialog(id);
    	
        switch (id) 
        {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(KidsTubeActivity.this);
                mProgressDialog.setMessage("Downloading file..");
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);
                return mProgressDialog;
            case DIALOG_QUIT_ALERT:
            	new AlertDialog.Builder(this)
    			.setMessage("Are you sure you want to quit?")
    			.setPositiveButton("Yes", new DialogInterface.OnClickListener()
    			{
					
					public void onClick(DialogInterface dialog, int which) 
					{
						finish();
					}
				})
				.setNegativeButton("No", null).show();
            	
            	return null;
            case DIALOG_DOWNLOAD_MGT:
            	new AlertDialog.Builder(this)
            	.setTitle("Download")
            	.setItems(dn_items, new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						System.out.println(dn_url[which]);
						
	        			if(android.os.Build.VERSION.SDK_INT > 8)
	        			{
							startDownloadMgt(Uri.parse(dn_url[which]), false, title, video_id + ".mp4");
							
							Intent i = new Intent();
					        i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
					        startActivity(i);
	        			}
						else
							new DownloadFileAsync().execute(dn_url[which], video_id + ".mp4");
						
						//removeDialog(DIALOG_DOWNLOAD_MGT);
					}
				})
				.show();
            	
            	return null;
            case DIALOG_LIMIT_ALERT:
            	new AlertDialog.Builder(this)
    			.setMessage("Please download the unlimited & NoAD version for a nominal fee to support our developers.")
    			.setPositiveButton("Yes", new DialogInterface.OnClickListener()
    			{
    				public void onClick(DialogInterface dialog, int which) 
    				{
    					Intent marketLaunch = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.snsoft.kidstubeplus"));
    					//Intent marketLaunch = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.tstore.co.kr/userpoc/mp.jsp?pid=0000290267"));
    					startActivity(marketLaunch);
    				}
    			})
    			.setNegativeButton("No", null).show();
            	return null;
            case DIALOG_DOWNLOAD_CHECK:
                mProgressDialog = new ProgressDialog(KidsTubeActivity.this);
                mProgressDialog.setMessage("Checking the download file...");
                mProgressDialog.setCancelable(false);
                return mProgressDialog;
            default:
                return null;
        }
    }

    // File download
    class DownloadFileAsync extends AsyncTask<String, String, String> 
    {
        
		@Override
		protected void onPreExecute() 
		{
			super.onPreExecute();
			showDialog(DIALOG_DOWNLOAD_PROGRESS);
		}

        @Override
        protected String doInBackground(String... aurl) 
        {
            int count;

            try 
            {
                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
                
                String sd = Environment.getExternalStorageDirectory().toString();
                
				File path = new File(sd + "/KidsTube");
				
				if(!path.isDirectory()) 
				{
					path.mkdirs();
				}
       	     
    			String fn = aurl[1];
    			f = new File(path, fn);

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(f.getAbsolutePath());

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) 
                {
                    total += count;
                    publishProgress(""+(int)((total*100)/lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {}
            return null;

        }
        
        protected void onProgressUpdate(String... progress) 
        {
             Log.d("ANDRO_ASYNC",progress[0]);
             mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) 
        {
            //dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            removeDialog(DIALOG_DOWNLOAD_PROGRESS);
            // Play mp4
            Intent intent = new Intent();  
            intent.setAction(android.content.Intent.ACTION_VIEW);  
            intent.setDataAndType(Uri.fromFile(f), "video/*");  
            startActivity(intent);
            
        }
    }
    
    // Checking the download file
    class DownloadUrlAsync extends AsyncTask<String, String, String> 
    {
        
		@Override
		protected void onPreExecute() 
		{
			super.onPreExecute();
			showDialog(DIALOG_DOWNLOAD_CHECK);
		}

        @Override
        protected String doInBackground(String... yturl) 
        {
    		int i = 0; 
    		
    		
    		String pageSource = "";
    		String fmt_url_map = "";
    		
    		while(i < 100) 
    		{ 
    			try
    			{
    				pageSource = getURLDATA("http://www.youtube.com/watch?v=" + video_id);
    				
    				//System.out.println(pageSource);
    				
    				title = null;
    				
    				if (title == null) title = inbtwn(pageSource, "name=\"title\" content=\"", "\"");
    				if (title == null) title = URLDecoder.decode(inbtwn(pageSource, "&title=", "&"), "UTF-8").replace("+", " "); 
    				
    				try {title = setHTMLEntity(title); } catch (Exception ex) { ex.printStackTrace(); }
    				
    				System.out.println("Title: " + title + "\r\n");
    	          
    				//fmt_url_map = URLDecoder.decode(inbtwn(pageSource, "url_encoded_fmt_stream_map=", "&"), "UTF-8");
    	          
    				fmt_url_map = inbtwn(pageSource, "url_encoded_fmt_stream_map\": \"", "\"").replace("\\/", "/");
    				System.out.println("url_encoded_fmt_stream_map: " + fmt_url_map + "\r\n");
    	          
    				/*
    				String dl_3gplow = null;
    				String dl_3gpmed = null;
    				String dl_3gphigh = null;
    				String dl_flvlow = null;
    				String dl_flvmed = null;
    				String dl_flvmed2 = null;
    				String dl_flvhigh = null;
    				String dl_mp4high = null;
    				String dl_mp4hd = null;
    				String dl_mp4hd2 = null;
    				String dl_mp4hd3 = null;
    				String dl_webmhd = null;
    				String dl_webmhd2 = null;
    				*/
    				
    				String[] fmt_arr = fmt_url_map.split("url=");
    				String split_url = "";
    				String split_items = "";
    				
    				for (String fmt : fmt_arr) 
    				{
    					String[] parts = fmt.split(",");
    					String m_url = URLDecoder.decode(parts[0], "UTF-8");
    					
    					m_url = m_url.replaceFirst("\".*", "").replace("%25","%").replace("\\u0026", "&").replace("\\", "");
    					m_url = m_url.replaceAll("%3F","?").replaceAll("%2F", "/").replaceAll("%3D","=").replaceAll("%26", "&").replaceAll("\\u0026", "&").replaceAll("%252C", "%2C").replaceAll("sig=", "signature=").replaceAll("x-flv", "flv");

    					
    					if(m_url.contains("http"))
    					{
    						/*
    						if (m_url.contains("itag=13"))
    						{
    							split_items += "[LD]114p 3gp@";
    							split_url += m_url + "@";
    						}
    						
    						if (m_url.contains("itag=6"))
    						{
    							split_items += "[SD]360p flv/webm@";
    							split_url += m_url + "@";
    						}
    						
    						if (m_url.contains("itag=38"))
    						{
    							split_items += "[HD]720p mpg@";
    							split_url += m_url + "@";
    						}
    						*/
    						/*
    						if (m_url.contains("itag=17"))
    						{
    							split_items += "[LD]114p mpg@";
    							split_url += m_url + "@";
    						}
    						*/
    						/*
    						if (m_url.contains("itag=36"))
    						{
    							split_items += "[LD]240p mpg@";
    							split_url += m_url + "@";
    						}
    						*/
    						if (m_url.contains("itag=34"))
    						{
    							split_items += "360p mpg@";
    							split_url += m_url + "@";
    						}
    						
    						/*
    						if (m_url.contains("itag=18"))
    						{
    							split_items += "[HQ]360p mpg@";
    							split_url += m_url + "@";
    						}
    						*/
    						if (m_url.contains("itag=35"))
    						{
    							split_items += "480p mpg@";
    							split_url += m_url + "@";
    						}
    						
    						/*
    						if (m_url.contains("itag=22"))
    						{
    							split_items += "[HD]720p mpg@";
    							split_url += m_url + "@";
    						}
    						*/
    						/*
    						if (m_url.contains("itag=37"))
    						{
    							split_items += "[HD]1080p mpg@";
    							split_url += m_url + "@";
    						}
    						*/
    						/*
    						if (m_url.contains("itag=5"))
    						{
    							split_items += "240p flv/webm@";
    							split_url += m_url + "@";
    						}
    						*/
    						/*
    						if (m_url.contains("itag=43"))
    						{
    							split_items += "[SD]360p flv/webm@";
    							split_url += m_url + "@";
    						}
    						*/
    						/*
    						if (m_url.contains("itag=44"))
    						{
    							split_items += "[SD]480p flv/webm@";
    							split_url += m_url + "@";
    						}
    						*/
    						/*
    						if (m_url.contains("itag=45"))
    						{
    							split_items += "[HD]720p flv/webm@";
    							split_url += m_url + "@";
    						}
    						*/
    						
    						/*
    						if (m_url.contains("itag=46"))
    						{
    							split_items += "[HD]1080p flv/webm@";
    							split_url += m_url + "@";
    						}
    						*/
    					}
    				}
    				
    				System.out.println(split_items);
    				
    				dn_items = split_items.split("@");
    				dn_url = split_url.split("@");
    				
    				URL chk_url = new URL(dn_url[0]);
    				HttpURLConnection connection = (HttpURLConnection) chk_url.openConnection();
    				
    				
    				if (connection.getResponseCode() != 403)
    					break;
    				else
    					i++;
    			}
    			catch(Exception ex)
    			{
    				ex.printStackTrace();
    			}
    		}
    		
    		return null;
        	
        }
        
        protected void onProgressUpdate(String... progress) 
        {
             Log.d("ANDRO_ASYNC",progress[0]);
        }

        @Override
        protected void onPostExecute(String unused) 
        {
        	removeDialog(DIALOG_DOWNLOAD_CHECK);
        	showDialog(DIALOG_DOWNLOAD_MGT);
        }
    }
    
    private String inbtwn(String a, String b, String c)
    {
      try {
        String[] arr1 = a.split(b);
        try {
          String[] arr2 = arr1[1].split(c);
          if ((arr2[0] != null) || (arr2[0] != "")) return arr2[0]; 
        }
        catch (Exception ex) {
          return arr1[1];
        }
        return arr1[1]; } catch (Exception ex) {
      }
      return null;
    }
    
    private String setHTMLEntity(String input)
    {
      String output = "";
      try {
        output = input.replace("&amp;", "").toString().replace("&lt;", "").toString().replace("&gt;", "").toString().replace("&#39;", "").toString().replace("&quot;", "").toString().replace("&", "").toString().replace("amp;", "").toString().replace("\\\"", "").toString().replace("\\'", "").toString().replace("'", "").toString().replace("'", "").toString().replace("<", "").toString().replace(">", "").toString().replace("?", "").toString().replace("/", "").toString().replace(":", "").toString().replace(";", "").toString().replace("#", "").toString();
      }
      catch (Exception e)
      {
        e.printStackTrace();
        return input;
      }
      return output;
    }
    
    private String getURLDATA(String url) throws IOException
    {

    	HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
         
        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params,schReg);
         
        DefaultHttpClient client = new DefaultHttpClient(conMgr, params);
        
        HttpUriRequest request = new HttpGet(url);
        
        HttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) 
            throw new IOException("Unexpected Http status code " + response.getStatusLine().getStatusCode());
         
        HttpEntity entity = response.getEntity();
        String result = null;
 
        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }
        
        return result;
    }
    
    // downloadUri -> Uri.parser("http://sample/sample.file");
    public void startDownloadMgt(Uri downloadUri, boolean onlyWifi, String title, String fn)
    {
    	
    	Environment.getExternalStoragePublicDirectory("KidsTube").mkdirs();
    	
        DownloadManager.Request request = new DownloadManager.Request(downloadUri);
        
        request.setTitle(title); // Notification에서 보여질 Main String 입니다.
        request.setDescription("S&TV-KIDS");
        request.setAllowedOverRoaming(false);
        request.setDestinationInExternalPublicDir("KidsTube", fn);
     
        if (onlyWifi)
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        else
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
     
       // final DownloadManager dManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
        downloadManager.enqueue(request);
    }
    
    @Override
    protected void onResume() {
     // TODO Auto-generated method stub
     super.onResume();

     IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
     registerReceiver(downloadReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
     // TODO Auto-generated method stub
     super.onPause();
     unregisterReceiver(downloadReceiver);
    }
    
    private BroadcastReceiver downloadReceiver = new BroadcastReceiver() 
	{
	
    	@Override
    	public void onReceive(Context arg0, Intent arg1)
    	{
    		// TODO Auto-generated method stub
    		DownloadManager.Query query = new DownloadManager.Query();
	   
    		query.setFilterById(preferenceManager.getLong(strPref_Download_ID, 0));
	   
    		Cursor cursor = downloadManager.query(query);
    		
    		if(cursor.moveToFirst())
    		{
    			//String uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
    			
    			int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
    			int status = cursor.getInt(columnIndex);
    			    			
    			if(status == DownloadManager.STATUS_SUCCESSFUL)
    			{
    				/*
    				//Retrieve the saved request id
    				long downloadID = preferenceManager.getLong(strPref_Download_ID, 0);
	 
    				ParcelFileDescriptor file;
    				
    				try
    				{
    					file = downloadManager.openDownloadedFile(downloadID);
    					
    					FileInputStream fileInputStream = new ParcelFileDescriptor.AutoCloseInputStream(file);
    					
						Intent intent = new Intent();  
						intent.setAction(android.content.Intent.ACTION_VIEW);  
						intent.setDataAndType(Uri.parse(uri), "video/*");
						
						startActivity(intent);
  
 						
    				} catch (FileNotFoundException e) 
    				{
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    				*/
    			}
    			else if(status == DownloadManager.STATUS_FAILED)
    			{
    				downloadManager.remove(preferenceManager.getLong(strPref_Download_ID, 0));
    				preferenceManager.edit().clear().commit();
    			}
    		}
    	}
    };
    
    public void onNtcComplete()
    {
    	NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		final Notification notice = new Notification(android.R.drawable.stat_sys_download, "Download is complete.", System.currentTimeMillis());
		PendingIntent launchIntent = PendingIntent.getActivity(activity, 0, new Intent(), 0);
        
		notice.setLatestEventInfo(activity, "t1", "ex", launchIntent);
		
		//알림
		mNotificationManager.notify(1, notice);

		//제거
		mNotificationManager.cancel(1);

    }
}